<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="/assets/addons/yalimedia/libs/jquery.min.js"></script>
    <script src="/assets/addons/yalimedia/libs/aliyun-upload-sdk-1.5.0.min.js"></script>
    <script src="/assets/addons/yalimedia/libs/es6-promise.min.js"></script>
    <script src="/assets/addons/yalimedia/libs/aliyun-oss-sdk-5.3.1.min.js"></script>
    <script src="/assets/addons/yalimedia/libs/jstree/jstree.min.js"></script>
    <link rel="stylesheet" href="/assets/addons/yalimedia/libs/jstree/themes/default/style.min.css" />
    <link rel="stylesheet" href="/assets/libs/font-awesome/css/font-awesome.min.css" />
    <style type="text/css">
        body{
            padding: 10px;
        }
        .container {
            width: 1200px;
            margin: 0 auto;
        }
        .input-control {
            margin: 5px 0;
        }
        .input-control label {
            font-size: 14px;
            color: #333;
            width: 30%;
            text-align: right;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }
        .input-control input {
            width: 30%;
            height: 30px;
            padding: 0 5px;
        }
        .upload {
            /*padding: 11px 11px;*/
            width: 100%;
        }
        .progress {
            font-size: 14px;
        }
        .progress i {
            font-style: normal;
        }
        .upload-type {
            color: #666;
            font-size: 12px;
        }
        .upload-type button  {
            margin: 0 10px 0 80px;
            background: #18bc9c;
            border: none;
            padding: 8px 15px;
            color: #fff;
        }
        .status {
            font-size: 14px;
            margin-left: 30px;
        }
        .info {
            font-size: 14px;
            padding-left: 30px;
        }
        .upload-flex{
            display: flex;
            align-items: center;
            color: #a2a2a2;
            font-size: 14px;
            margin-bottom: 18px;
        }
        .upload-title{width: 78px;}
        #cate{
            width: 320px;
            padding: 8px;
            border:solid 1px #dedede;
        }
        .upload-box-table table td{
            padding: 12px;
            border-bottom: solid 1px #ececec;
        }
        .upload-box-table-text{
            max-width: 102px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .upload-box-table span{
            font-size: 14px;
            color: red;
        }
    </style>

</head>
<body>
<div>
    
    
        <div class="upload">
   
            
        
                        
                
                    
            <div class="upload-flex">
                <div class="upload-title">上传到</div>
                <input id="cateId" type="hidden" value="{$cateId}">
                <div>
                    <input id="cate" value="{$cateName}" readonly>
                    <div id="jstree_area" style="border:1px solid #eee;position: fixed;width: 334px; height: 400px; display:none;overflow-y:auto; z-index: 9999999;background: #fff;"></div>
                </div>
            </div>
     
            
            <div class="upload-flex upload-type" id="uploadBtn" >
                <div class="upload-title">本地文件</div>
                <button style="margin-left: 0;cursor:pointer;" id="upload_btn" >选择文件</button>
                <div style="display: none;">
                    
                    <form id="uploadForm" name="uploadForm"  method="post" enctype="multipart/form-data">
                        {if condition="$type eq 1"}
                        <input type="file" id="fileUpload" multiple accept="image/*">
                        {elseif condition="$type eq 2"/}
                        <input type="file" id="fileUpload" multiple accept="audio/mpeg">
                        {else}
                        <input type="file" id="fileUpload" multiple accept="video/mp4">
                        {/if}
                    </form>
                </div>
            </div>

            <div id="file_table" style="display: none;">
    
                <div class="upload-flex" style="align-items: flex-start;">
                    <div class="upload-title">本地文件</div>
                    <div style="flex: 1;">
                        <div class="upload-box-table">
                            <table id="fileListTable" class="table table-striped table-bordered table-hover" width="96%"  border="0" cellspacing="0" cellpadding="0" style="text-align:center;color: #444;">
                                <tr style="background: #f5f5f5;height: 32px;font-weight: bold;">
                                    <td>文件名</td>
                                    <td>大小</td>
                                    <td>上传进度</td>
                                    <td>操作</td>
                                </tr>
    
                            </table>
                        </div>
                    </div>
    
                </div>
                <div class="upload-flex upload-type" >
                    <div class="upload-title"></div>
                    <button id="authUpload" style="margin-left: 0">开始上传</button>
                    <span id="success" style=" display:none;color: #f00;">全部上传成功</span>
                </div>
                
            </div>
            
            
           
 
 
        </div>
    
   
    
</div>
<script>

    //兼容IE11
    if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function (fileData) {
            var binary = "";
            var pt = this;
            var reader = new FileReader();
            reader.onload = function (e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                //pt.result  - readonly so assign binary
                pt.content = binary;
                pt.onload()
            }
            reader.readAsArrayBuffer(fileData);
        }
    }

    //处理文件大小
    getMediaSize = function(limit){
        var size = "";
        if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
            size = limit.toFixed(2) + "B"
        }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
            size = (limit/1024).toFixed(2) + "KB"
        }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
            size = (limit/(1024 * 1024)).toFixed(2) + "MB"
        }else{                                            //其他转化成GB
            size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
        }

        var sizeStr = size + "";                        //转成字符串
        var index = sizeStr.indexOf(".");                    //获取小数点处的索引
        var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
        if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
            return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
        }
        return size;
    }

    /**
     * 创建一个上传对象
     */
    createUploader = function() {

        var uploader = new AliyunUpload.Vod({
            timeout: $('#timeout').val() || 60000,
            partSize: $('#partSize').val() || 1048576,
            parallel: $('#parallel').val() || 5,
            retryCount: $('#retryCount').val() || 3,
            retryDuration: $('#retryDuration').val() || 2,
            region: "{$regionId}",
            cateId:$("#cateId").val(),
            userId: "1089642645862335",
            // 添加文件成功
            addFileSuccess: function (uploadInfo) {

                var size = getMediaSize(uploadInfo['file']['size']);
                $("#fileListTable").append(`<tr>
                            <td class="upload-box-table-text" id="filename">${uploadInfo['file']['name']}</td>
                                <td id="filesize">${size}</td>
                                <td style="display: flex;align-items: center;justify-content: center"><div id="${uploadInfo['ri']}">0</div><div>%</div></td>
                            <td><span data-ri="${uploadInfo['ri']}" class="removeBtn" onclick="removeMedia(this)">移除</span></td>
                            </tr>
                            `)

                $("#file_table").show();
                $("#uploadBtn").hide();
                $('#authUpload').attr('disabled', false)
            },
            // 开始上传
            onUploadstarted: function (uploadInfo) {
                
                
                // var formData = new FormData($('#uploadForm')[0]);
                // console.log(FormData);
                // $.ajax({
                //     url: 'https://nhnbo.dgqmkj.site/api/Common/upload',
                //     type: 'POST',
                //     data: formData,
                //     processData: false,
                //     contentType: false,
          
                //     success: function(result) {
                //         if (result.success) {
                //             alert('上传成功！');
                //         } else {
                //             alert('上传失败，请重试。');
                //         }
                //     },
                //     error: function() {
                //         alert('上传失败，请重试。');
                //     }
                // });


                // console.log(uploadInfo);
                // console.log($("#fileUpload").val());
                // console.log($("#cate").val());
                
                if (!uploadInfo.videoId) {
                    $(".removeBtn").hide();

                    var cateId = $("#cateId").val();
                    var transcode = 1;
                    
                    if(uploadInfo.isImage == true){
                        var createUrl = 'CreateUploadImage?titleName='+uploadInfo.file.name+'&fileName='+uploadInfo.file.name+'&fileSize='+uploadInfo.file.size+'&cateId='+cateId+"&transcode="+transcode
                    }else{
                        var createUrl = 'createUploadVideo?titleName='+uploadInfo.file.name+'&fileName='+uploadInfo.file.name+'&fileSize='+uploadInfo.file.size+'&cateId='+cateId+"&transcode="+transcode
                    }
                   
                    $.get(createUrl, function (data) {
                     
                        if(data.code == 0){
                            alert(data.msg);
                            return;
                        }
                        var uploadAuth = data.UploadAuth
                        var uploadAddress = data.UploadAddress
                        var videoId = data.VideoId
                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
                    }, 'json')
                } else {
                    var createUrl = 'refreshUploadVideo?videoid='+uploadInfo.videoId+'&fileSize='+uploadInfo.file.size

                    $.get(createUrl, function (data) {
                        if(data.code == 0){
                            alert(data.msg);
                            return;
                        }
                        var uploadAuth = data.UploadAuth
                        var uploadAddress = data.UploadAddress
                        var videoId = data.VideoId
                        uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
                    }, 'json')
                }
                
                
                
            },
            onUploadProgress: function (uploadInfo, totalSize, progress) {
                var progressPercent = Math.ceil(progress * 100)
                $('#'+uploadInfo['ri']).html(progressPercent)
            },
            // 全部文件上传结束
            onUploadEnd: function () {
                setTimeout(function () {
                    parent.$("a.btn-refresh").trigger("click");
                },500)
                $("#success").show()

            }
        })
        return uploader
    }


    $(document).ready(function () {

        $('#jstree_area').jstree({
            "core" : {

                "check_callback" : true,
                "themes": {
                    "stripes": false,
                    "dots": false,//是否显示树连接线
                    "icons": true,//是否显示节点的图标
                },

                'data':{
                    'url' : 'upload_tree',
                    'data' : function (node) {
                        return { 'id' : node.id,'type': {$type}};
                    }
                },
            },
            "types": {
                "total": {"icon": "fa fa-folder-o",},
                "folder": {"icon": "fa fa-folder",},
                "disabled": {"check_node": false,"uncheck_node": false}
            },
            'plugins': ["types"],
        });

        $('#jstree_area').on("changed.jstree", function (e, data) {
            if(data.node){
                $("#cate").val(data.node.text);
                $("#cateId").val(data.node.id);
                $('#jstree_area').hide()
            }

        });

        $(document).click(function (event) {
            var _con = $('#jstree_area');  // 设置目标区域
            if(!_con.is(event.target) && _con.has(event.target).length === 0){ // Mark 1
                $('#jstree_area').hide()
            }
        });

        $("#cate").click(function (event) {
            event.stopPropagation();
            $('#jstree_area').show()
        })


        $("#upload_btn").click(function () {
            if($('#cateId').val() == '0'){alert('请选择分类');return;}
            $('#fileUpload').click();
        })



        removeMedia = function (item) {
            var list = uploader.listFiles();
            for (var i=0; i<list.length; i++) {
                if(list[i].ri == $(item).data('ri')){
                    uploader.deleteFile(i);
                    $(item).parent().parent().remove();
                }
            }
        }


        var uploader = null
        $("#fileRemoveBtn").click(function () {
            $("#success").hide();
            $("#file_table").hide();
            $("#uploadBtn").show();
            $("#fileUpload").val("");
        })

        $('#fileUpload').on('change', function (e) {
            uploader = createUploader()
            for(var i=0; i<e.target.files.length; i++) {
                var file = e.target.files[i]
                if (!file) {
                    alert("请先选择需要上传的文件!")
                    return
                }
                var Title = file.name
                var userData = '{"Vod":{}}'
                if (uploader) {
                    uploader.stopUpload()
                    $('#auth-progress').text('0')
                    $('#status').text("")
                }

                uploader.addFile(file, null, null, null, userData)
                $('#authUpload').attr('disabled', false)
                $('#pauseUpload').attr('disabled', true)
                $('#resumeUpload').attr('disabled', true)
            }





        })

        $('#authUpload').on('click', function () {
            // 然后调用 startUpload 方法, 开始上传
            if (uploader !== null) {
                
                // var form     = document.getElementById("uploadForm");
                // var formData = new FormData(form);
                
                // $.ajax({
                //     url: 'https://nhnbo.dgqmkj.site/api/Common/upload',
                //     type: 'POST',
                //     data: formData,
                //     processData: false,
                //     contentType: false,
          
                //     success: function(result) {
                //         if (result.success) {
                //             alert('上传成功！');
                //         } else {
                //             alert('上传失败，请重试。');
                //         }
                //     },
                //     error: function() {
                //         alert('上传失败，请重试。');
                //     }
                // });
                
                
                // // var formData = new FormData($('#uploadForm')[0]);
                // // console.log(FormData);
                
                // // console.log(uploader);
                uploader.startUpload()
                $('#authUpload').attr('disabled', true)
                $('#pauseUpload').attr('disabled', false)
            }
        })


    })
</script>
</body>
</html>